import {Component, OnInit, Input, Output, HostListener, EventEmitter, ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'seed-badge-follow',
  templateUrl: './follow.component.html',
  styleUrls: ['./follow.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class FollowComponent implements OnInit {
  public index: number;
  public loading: boolean;
  private _isFollowed: number;
  private _isFollowedMe: number;
  private timer: any;

  @Input()
  set isFollowed(val: number) {
    this._isFollowed = val;
    this.followHandler(val, this.isFollowedMe);
  }

  get isFollowed() {
    return this._isFollowed;
  }

  @Input()
  set isFollowedMe(val: number) {
    this._isFollowedMe = val;
    this.followHandler(this.isFollowed, val);
  }

  get isFollowedMe() {
    return this._isFollowedMe;
  }

  @Output() onFollowing: EventEmitter<number> = new EventEmitter();

  constructor() {
    this.loading = false;
  }

  @HostListener('click', ['$event.target'])
  clickHandler() {
    this.loading = true;
    if (this.timer) {
      clearTimeout(this.timer);
    };
    this.timer = setTimeout(() => {
      this.loading = false;
      this.onFollowing.emit(this.index);
    }, 800);
  }

  followHandler(isFollowed: number, isFollowedMe: number) {
    if (isFollowed === 0) {
      this.index = 0;
    }else if (isFollowed === 1 && isFollowedMe === 0) {
      this.index = 1;
    }else if (isFollowed === 1 && isFollowedMe === 1) {
      this.index = 2;
    } else {
      this.index = 0;
    }
  }

  ngOnInit() {
  }

}
